<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <!-- <div v-if="!flag" class="title1">
      <div class="step1-form"
        style="width: 500px;border: 1px solid #aaa;padding: 30px 35px 30px 20px;border-radius: 10px;">
        <div style="font-weight: bold;font-size: 30px;text-align: center;margin-bottom: 50px;">
          选择公司
        </div>
        <BasicForm @register="registerForm2" style="padding: none;">
        </BasicForm>
        <div style="width: 100%;display: flex;justify-content: center;margin-top: 100px;padding-left: 15px;">
          <a-button style="width: 100%;" type="primary" @click="handleXzgs">下一步</a-button>
        </div>
      </div>
    </div> v-if="flag"-->
    <div class="title1">
      <div>
        <BasicTable @register="registerTable" @edit-change="rowChange">
          <template #tableTitle>
            <div style="display: flex; align-items: center; overflow: hidden">
              <Icon :icon="getTitle.icon" class="m-1 pr-1" />
              <span class="mr-2"> 待开票区 </span>
              <!-- <span >【{{companyData.name}}】</span> -->
              <!-- <TreeSelect
              :value="companyData.code"
              :labelValue="companyData.name"
              :api="companyTreeData()"
              :params="{ isShowCode: true }"
              :canSelectParent="false"
              :treeCheckable="false"
              :immediate="true"
              :placeholder="'（公司编号）公司名称'"
            /> -->
              <BasicForm
                @register="registerForm2"
                style="margin-top: -5px; margin-bottom: -15px; width: 600px"
              >
              </BasicForm>
            </div>
          </template>
          <template #toolbar>
            <a-button
              type="success"
              ghost
              @click="handleAddBh()"
              v-auth="'srm:cw:prekp:puGeneralPreData:edit'"
            >
              <Icon icon="i-fluent:add-12-filled" /> {{ t('添加至准备区') }}
            </a-button>

            <!-- <a-button type="warning" ghost @click="handlefp" v-auth="'srm:asn:create:edit'">
              <Icon icon="i-fluent:add-12-filled" /> {{ t('自动分配') }}
            </a-button> -->
          </template>
          <template #firstColumn="{ record }">
            <a @click="handleForm({ id: record.id })">
              {{ record.unitname }}
            </a>
          </template>

          <template #summary>
            <TableSummary fixed>
              <TableSummaryRow>
                <TableSummaryCell :index="0" :col-span="2" align="center">
                  合计：
                </TableSummaryCell>

                <TableSummaryCell :index="2" :col-span="4"> </TableSummaryCell>
                <TableSummaryCell :index="6" align="center">
                  {{ totals[0] }}
                </TableSummaryCell>
                <TableSummaryCell :index="7" align="center">
                  {{ totals[1] }}
                </TableSummaryCell>
                <TableSummaryCell :index="8" align="center">
                  {{ totals[2] }}
                </TableSummaryCell>
                <TableSummaryCell :index="9" align="center">
                  {{ totals[3] }}
                </TableSummaryCell>
                <TableSummaryCell :index="10" align="center">
                  {{ totals[4] }}
                </TableSummaryCell>
                <TableSummaryCell :index="11" align="center">
                  <span style="color: red; font-weight: bold">{{ shNum }}</span>
                </TableSummaryCell>
                <TableSummaryCell :index="12"> </TableSummaryCell>
                <TableSummaryCell :index="13" align="center">
                  {{ totals[5] }}
                </TableSummaryCell>
                <TableSummaryCell :index="14"> </TableSummaryCell>
                <TableSummaryCell :index="15" align="center">
                  {{ totals[6] }}
                </TableSummaryCell>
                <TableSummaryCell :index="16"> </TableSummaryCell>
                <TableSummaryCell :index="17" align="center">
                  {{ totals[7] }}
                </TableSummaryCell>
                <TableSummaryCell :index="18" :col-span="15"> </TableSummaryCell>
                <!-- <TableSummaryCell v-for="(item, index) in totals" :index="index" align="center"
                >{{ item }}
              </TableSummaryCell> -->
              </TableSummaryRow>
            </TableSummary>
          </template>
        </BasicTable>
      </div>
      <div class="lg:flex !mt-4" style="flex: 1">
        <!-- <div class="lg:w-3/10 enter-y !mr-4" style="background: #fff;">
            <BasicTable @register="registerTable2" @row-click="handleRowClick">
              <template #tableTitle>
                <Icon :icon="getTitle.icon" class="m-1 pr-1" />
                <span> 分组区 </span>
              </template>
            </BasicTable>
          </div> -->
        <div class="lg:w-10/10 enter-y" style="background: #fff">
          <BasicTable @register="registerTable3">
            <template #tableTitle>
              <Icon :icon="getTitle.icon" class="m-1 pr-1" />
              <span> 准备区</span>
              <!-- <span class="ml-2" style="font-weight: bold;color: red;">【说明：备货区记录仅24小时内有效；失效后将会自动清空】</span> -->
            </template>
            <template #toolbar>
              <!-- <a-button type="error" ghost @click="handleForm" v-auth="'puorder:poorder:edit'">
                  <Icon icon="ant-design:delete-outlined" /> {{ t('清除选择行') }}
                </a-button>
                <Popconfirm :title="t('是否确认订单？')" @confirm="handleRr()">
                <a-button type="success" ghost @click="handleModal" v-auth="'puorder:poorder:comfirm'">
                  <Icon icon="i-ant-design:check-outlined" /> {{ t('生成送货单') }}
                </a-button>
                </Popconfirm> -->
              <Dropdown placement="bottom" :trigger="['click']">
                <a-button type="error" ghost @click.prevent v-auth="'srm:cw:prekp:puGeneralPreData:edit'">
                  <Icon icon="ant-design:delete-outlined" /> {{ t('清除准备区') }}
                </a-button>
                <template #overlay>
                  <Menu>
                    <!-- v-if="hasPermission(['btn:proj:material:infoclqd'])" -->
                    <MenuItem @click="handlegx" v-if="hasPermission(['srm:cw:gx:br:delete'])">
                      <span>勾选记录清除</span>
                    </MenuItem>
                    <MenuDivider />
                    <MenuItem @click="handlegys" v-if="hasPermission(['srm:cw:gys:yh:delete'])">
                      <span>按供应商清除</span>
                    </MenuItem>
                    <MenuDivider />
                    <MenuItem @click="handlebr" v-if="hasPermission(['srm:cw:gx:br:delete'])">
                      <span>本人数据清除</span>
                    </MenuItem>
                    <MenuDivider />
                    <MenuItem @click="handlexzyh" v-if="hasPermission(['srm:cw:gys:yh:delete'])">
                      <span>选择用户清除</span>
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown>

              <Dropdown placement="bottom" :trigger="['click']">
                <a-button type="success" ghost @click.prevent v-auth="'srm:cw:prekp:puGeneralPreData:edit'">
                  <Icon icon="i-ant-design:check-outlined" /> {{ t('生成开票通知单') }}
                </a-button>
                <template #overlay>
                  <Menu>
                    <MenuItem @click="handleGxsd">
                      <span>勾选生单</span>
                    </MenuItem>
                    <MenuDivider />
                    <MenuItem @click="handleYjsd">
                      <span>一键生单</span>
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown>
            </template>

            <template #summary>
              <TableSummary fixed>
                <TableSummaryRow>
                  <TableSummaryCell :index="0" :col-span="2" align="center">
                    合计：
                  </TableSummaryCell>
                  <TableSummaryCell :index="2" :col-span="7"> </TableSummaryCell>
                  <TableSummaryCell :index="9" align="center">
                    {{ kpQty }}
                  </TableSummaryCell>
                  <TableSummaryCell :index="10" :col-span="7"> </TableSummaryCell>
                </TableSummaryRow>
              </TableSummary>
            </template>
          </BasicTable>
        </div>
      </div>

      <BasicModal v-bind="$attrs" @register="registerModal" title="自动分配" @ok="handleQr">
        <BasicForm @register="registerForm" />
      </BasicModal>

      <!-- 供应商 -->
      <ListSelect
        ref="listSelectRefGys"
        selectType="basVenSelect"
        :checkbox="false"
        @select="handleSelectGys"
        v-show="false"
      />

      <!-- 用户 -->
      <ListSelect
        ref="listSelectRefUser"
        selectType="empUserSelect"
        :checkbox="false"
        @select="handleSelectUser"
        v-show="false"
      />
    </div>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsSrmCwBillvouchPuGeneralList',
    components: { Menu, Dropdown, MenuItem: Menu.Item, MenuDivider: Menu.Divider },
  });
</script>
<script lang="ts" setup>
  import { unref, onMounted, computed, ref, defineComponent } from 'vue';
  import { TreeSelect, Menu, Dropdown } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    // puOrderPreDataNeedShListData,
    // puOrderPreDataListData,
    // puOrderPreDataGroupListData,
    // puOrderPreDataSave,
    puGeneralPreDataDelete,
    puGeneralPreDataPushKpBill,
  } from '/@/api/srm/cw/prekp/puGeneralPreData';
  import {
    puGeneralDelete,
    puGeneralPreDataListData,
    puGeneralNeedKpListData,
    puGeneralPreDataSave,
  } from '/@/api/srm/cw/billvouch/puGeneral';
  import { puBillVouchCalcMoney } from '/@/api/srm/cw/billvouch/puBillVouch';

  import { useDrawer, useDrawerInner, BasicDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { PageWrapper } from '/@/components/Page';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { ListSelect } from '/@/components/ListSelect';
  import { TableSummary, TableSummaryCell, TableSummaryRow } from 'ant-design-vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { NumEnum } from '/@/enums/defEnum';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();

  const { t } = useI18n('puorder.poorder');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  // const selectedRowRef = ref<string[]>([]);

  let companyData = ref({});
  let venData = ref({});

  let searchInfo3 = ref({});

  const listSelectRefGys = ref<any>(null);
  const listSelectRefUser = ref<any>(null);

  let flag = ref(false);
  const selectedRowRef = computed(() => {
    let arr = getSelectRows();
    return arr;
  });

  const shNum = computed(() => {
    let arr = getSelectRows();
    let sum = 0;
    for (const record of arr) {
      let ntotalnum = record.editValueRefs.kpQty.value;
      sum += Number(ntotalnum);
    }
    return sum.toFixed(NumEnum.scaleSelQty);
  });

  const kpQty = computed(() => {
    let sumkpQty = 0;
    for (const record of getDataSource3()) {
      const { kpQty } = record;
      sumkpQty += Number(kpQty || 0);
    }
    return sumkpQty.toFixed(NumEnum.scaleSelQty);
  });

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    // value: meta.title || t('订单变更记录'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    submitFunc: () => {
      setTableData([]);
      reload();
    },
    // showResetButton:false,
    schemas: [
      // {
      //   label: t('公司名称'),
      //   field: 'unitname',
      //   component: 'Input',
      // },
      // {
      //   label: t('供应商'),
      //   field: 'parent.custName',
      //   component: 'Input',
      //   componentProps: {
      //     allowClear: true,
      //   },
      // },
      {
        label: t('入库日期'),
        field: 'dbilldate',
        component: 'RangePicker',
        componentProps: {},
      },

      {
        label: t('入库单号'),
        field: 'vbillcode',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('存货编码'),
        field: 'cinvcode',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('存货名称'),
        field: 'cinvname',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('规格'),
        field: 'cinvspec',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('型号'),
        field: 'cinvtype',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('批次号'),
        field: 'cbatch',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('仓库'),
        field: 'wareName',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('业务流程'),
        field: 'busTypeName',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('部门'),
        field: 'cgDeptName',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },

      {
        label: t('订单号'),
        field: 'orerCode',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },

      {
        label: t('订单日期'),
        field: 'orderDate',
        component: 'RangePicker',
        componentProps: {
          allowClear: true,
        },
      },

      {
        label: t('表体备注'),
        field: 'vnotebody',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('退货标志'),
        field: 'freplenishflag',
        component: 'Select',
        componentProps: {
          dictType: 'sys_y_n',
          allowClear: true,
        },
      },
    ],
    fieldMapToTime: [
      ['dbilldate', ['dbilldate_gte', 'dbilldate_lte']],
      ['orderDate', ['orderDate_gte', 'orderDate_lte']],
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('存货编码'),
      dataIndex: 'cinvcode',
      key: 'a.cinvcode',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'cinvname',
      key: 'a.cinvname',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('规格'),
      dataIndex: 'cinvspec',
      key: 'a.cinvspec',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('型号'),
      dataIndex: 'cinvtype',
      key: 'a.cinvtype',
      sorter: true,
      width: 130,
      align: 'left',
    },

    {
      title: t('入库数'),
      dataIndex: 'ninnum',
      width: 100,
      align: 'center',
    },
    {
      title: t('已准备数'),
      dataIndex: 'yzbQty',
      width: 100,
      align: 'center',
    },
    {
      title: t('已开票数'),
      dataIndex: 'ykpQty',
      width: 100,
      align: 'center',
    },
    {
      title: t('开票中数量'),
      dataIndex: 'kpzQty',
      width: 100,
      align: 'center',
    },
    {
      title: t('剩余开票数'),
      dataIndex: 'sykpQty',
      width: 100,
      align: 'center',
      customCell: (record: Recordable) => {
        const color = '#eaf4e1';
        return {
          // innerHTML: record.testTextarea, // 原样输出，不进行html编码（例子）
          style: `background-color: ${color} !important`,
          // style: `color: ${color} !important;font-size: ${size};`,
        };
      },
    },
    {
      title: t('本次开票数'),
      dataIndex: 'kpQty',
      width: 120,
      align: 'center',
      editComponent: 'InputNumber',
      editComponentProps: {
        min: 0,
      },
      edit: true,
      editable: true,
      customCell: (record: Recordable) => {
        const color = '#eaf4e1';
        return {
          // innerHTML: record.testTextarea, // 原样输出，不进行html编码（例子）
          style: `background-color: ${color} !important`,
          // style: `color: ${color} !important;font-size: ${size};`,
        };
      },
    },
    {
      title: t('无税单价'),
      dataIndex: 'nprice',
      // key: 'a.nprice',
      // sorter: true,
      width: 120,
      align: 'center',
      editComponent: 'InputNumber',
      editComponentProps: {
        min: 0,
      },
      edit: true,
      editable: true,
    },
    {
      title: t('无税金额'),
      dataIndex: 'nmny',
      // key: 'a.nmny',
      // sorter: true,
      width: 120,
      align: 'center',
      editComponent: 'InputNumber',
      editComponentProps: {
        min: 0,
      },
      edit: true,
      editable: true,
    },
    {
      title: t('含税单价'),
      dataIndex: 'ntaxprice',
      // key: 'a.ntaxprice',
      // sorter: true,
      width: 120,
      align: 'center',
      editComponent: 'InputNumber',
      editComponentProps: {
        min: 0,
      },
      edit: true,
      editable: true,
    },
    {
      title: t('含税金额'),
      dataIndex: 'ntaxmny',
      // key: 'a.ntaxmny',
      // sorter: true,
      width: 120,
      align: 'center',
      editComponent: 'InputNumber',
      editComponentProps: {
        min: 0,
      },
      edit: true,
      editable: true,
    },
    {
      title: t('税率'),
      dataIndex: 'nictaxrate',
      // key: 'a.nictaxrate',
      // sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('税额'),
      dataIndex: 'noritaxmny',
      // key: 'a.noritaxmny',
      // sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('单位'),
      dataIndex: 'measname',
      key: 'a.measname',
      sorter: true,
      width: 80,
      align: 'left',
    },
    {
      title: t('公司'),
      dataIndex: 'compName',
      key: 'a.pk_corp',
      sorter: true,
      width: 180,
      align: 'left',
    },
    {
      title: t('供应商'),
      dataIndex: 'venName',
      key: 'a.ven_name',
      sorter: true,
      width: 180,
      align: 'left',
    },
    {
      title: t('入库单号'),
      dataIndex: 'vbillcode',
      key: 'a.vbillcode',
      sorter: true,
      width: 130,
      align: 'left',
      //slot: 'firstColumn',
    },
    {
      title: t('入库日期'),
      dataIndex: 'dbilldate',
      key: 'a.dbilldate',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('行号'),
      dataIndex: 'crowno',
      key: 'a.crowno',
      sorter: true,
      width: 80,
      align: 'center',
    },
    {
      title: t('批次号'),
      dataIndex: 'cbatch',
      key: 'a.cbatch',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('币种'),
      dataIndex: 'currtypename',
      key: 'a.currtypename',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('仓库'),
      dataIndex: 'wareName',
      key: 'a.ware_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('业务流程'),
      dataIndex: 'busTypeName',
      key: 'a.bus_type_name',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('部门'),
      dataIndex: 'cgDeptName',
      key: 'a.cg_dept_name',
      sorter: true,
      width: 130,
      align: 'left',
    },

    {
      title: t('订单号'),
      dataIndex: 'orerCode',
      key: 'a.orer_code',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('订单日期'),
      dataIndex: 'orderDate',
      key: 'a.order_date',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('表头备注'),
      dataIndex: 'vnote',
      key: 'a.vnote',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('表体备注'),
      dataIndex: 'vnotebody',
      key: 'a.vnotebody',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'measname',
      key: 'a.measname',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('批次号'),
      dataIndex: 'cbatch',
      key: 'a.cbatch',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('币种'),
      dataIndex: 'currtypename',
      key: 'a.currtypename',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('仓库'),
      dataIndex: 'wareName',
      key: 'a.ware_name',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('业务流程'),
      dataIndex: 'busTypeName',
      key: 'a.bus_type_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('部门'),
      dataIndex: 'cgDeptName',
      key: 'a.cg_dept_name',
      sorter: true,
      width: 130,
      align: 'right',
    },

    {
      title: t('订单号'),
      dataIndex: 'orerCode',
      key: 'a.orer_code',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('订单日期'),
      dataIndex: 'orderDate',
      key: 'a.order_date',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('表头备注'),
      dataIndex: 'vnote',
      key: 'a.vnote',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('表体备注'),
      dataIndex: 'vnotebody',
      key: 'a.vnotebody',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('累计结算数量'),
      dataIndex: 'naccountnum1',
      key: 'a.naccountnum1',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('退货标志'),
      dataIndex: 'freplenishflag',
      key: 'a.freplenishflag',
      sorter: true,
      width: 100,
      align: 'left',
    },
  ];

  const table2Columns: BasicColumn[] = [
    {
      title: t('供应商'),
      dataIndex: 'venName',
      width: 100,
      align: 'left',
    },

    {
      title: t('业务流程'),
      dataIndex: 'busTypeName',
      width: 80,
      align: 'center',
    },
    {
      title: t('仓库'),
      dataIndex: 'wareName',
      width: 80,
      align: 'center',
    },
    {
      title: t('采购员'),
      dataIndex: 'cgName',
      width: 80,
      align: 'center',
    },
    {
      title: t('采购部门'),
      dataIndex: 'cgDeptName',
      width: 80,
      align: 'center',
    },
  ];

  const table3Columns: BasicColumn[] = [
    {
      title: t('入库单号'),
      dataIndex: 'rkCode',
      width: 130,
      align: 'left',
    },
    {
      title: t('入库日期'),
      dataIndex: 'rkDate',
      width: 130,
      align: 'left',
    },
    {
      title: t('存货编码'),
      dataIndex: 'puGeneral.cinvcode',
      width: 130,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'puGeneral.cinvname',
      width: 150,
      align: 'left',
    },
    {
      title: t('规格'),
      dataIndex: 'puGeneral.cinvspec',
      width: 120,
      align: 'left',
    },
    {
      title: t('型号'),
      dataIndex: 'puGeneral.cinvtype',
      width: 150,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'puGeneral.measname',
      width: 80,
      align: 'center',
    },

    {
      title: t('本次开票数'),
      dataIndex: 'kpQty',
      width: 100,
      align: 'center',
    },
    {
      title: t('无税单价'),
      dataIndex: 'nprice',
      width: 100,
      align: 'center',
    },
    {
      title: t('无税金额'),
      dataIndex: 'nmny',
      width: 100,
      align: 'center',
    },
    {
      title: t('含税单价'),
      dataIndex: 'ntaxprice',
      width: 100,
      align: 'center',
    },
    {
      title: t('含税金额'),
      dataIndex: 'ntaxmny',
      width: 100,
      align: 'center',
    },
    {
      title: t('税率'),
      dataIndex: 'nictaxrate',
      width: 100,
      align: 'center',
    },
    {
      title: t('税额'),
      dataIndex: 'noritaxmny',
      width: 100,
      align: 'center',
    },
    {
      title: t('订单号'),
      dataIndex: 'orderCode',
      width: 120,
      align: 'left',
    },
    {
      title: t('订单日期'),
      dataIndex: 'orderDate',
      width: 100,
      align: 'center',
    },
    // {
    //   title: t('采购员'),
    //   dataIndex: 'parent.psnName',
    //   width: 100,
    //   align: 'center',
    // },

    {
      title: t('备注信息'),
      dataIndex: 'remarks',
      width: 150,
      align: 'left',
    },
    // {
    //   title: t('供应商'),
    //   dataIndex: 'parent.custName',
    //   width: 200,
    //   align: 'left',
    // },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑采购订单'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'puorder:poorder:edit',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [
    registerTable,
    { reload, getForm, getDataSource, getSelectRows, setSelectedRowKeys, setTableData },
  ] = useTable({
    api: puGeneralNeedKpListData,
    beforeFetch: (params) => {
      params.pkCorp = companyData.value.code || '-1';
      params.venId = venData.value.id || '-1';
      return params;
    },
    afterFetch: (list) => {
      list.forEach((element) => {
        // element.kpQty = element.sykpQty < 0? 0:element.sykpQty;
        element.kpQty = element.sykpQty;
      });
      return list;
    },

    columns: tableColumns,
    //actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    // scroll: {
    //   y: 250,
    // },
    maxHeight: 250,
    rowSelection: {
      type: 'checkbox',
    },
    immediate: false,
  });

  // const [registerTable2, { reload: reload2 }] = useTable({
  //   api: puOrderPreDataGroupListData,
  //   beforeFetch: (params) => {
  //     params.pkCorp = companyData.value.code || '-1'
  //     return params;
  //   },
  //   columns: table2Columns,
  //   //actionColumn: actionColumn,
  //   formConfig: searchForm,
  //   showTableSetting: true,
  //   useSearchForm: false,
  //   // canResize: true, //表格是否flex布局
  //   // maxHeight: 600,
  //   immediate: false, //懒加载
  //   showIndexColumn: false,
  //   rowSelection: {
  //     type: 'radio',
  //   },
  //   rowKey:'id',
  //   pagination:false,
  //   isCanResizeParent:true
  // });

  const [
    registerTable3,
    {
      reload: reload3,
      setTableData: setTableData3,
      getDataSource: getDataSource3,
      getSelectRows: getSelectRows3,
    },
  ] = useTable({
    api: puGeneralPreDataListData,
    beforeFetch: (params) => {
      params.pkCorp = companyData.value.code || '-1';
      params.venId = venData.value.id || '-1';
      return params;
    },
    columns: table3Columns,
    //actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: false,
    // canResize: true, //表格是否flex布局
    // maxHeight: 600,

    immediate: false, //懒加载
    // tableSetting: {
    //   redo: false
    // },
    rowSelection: {
      type: 'checkbox',
    },
    isCanResizeParent: true,
  });

  const [registerForm2, { validate: validate2, setFieldsValue: setFieldsValue2 }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t(''),
        field: 'code',
        fieldLabel: 'name',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          params: {
            isShowCode: true,
          },
          canSelectParent: false,
          placeholder: '（公司编号）公司名称',
          // allowClear: true,
          immediate: true,
          onChange: async (e) => {
            companyData.value.code = e;
            if (venData.value.id) {
              await reload();
              await reload3();
            }
            // setTableData3([])
          },
        },
        // required: true,
      },
      {
        label: t(''),
        field: 'venId',
        fieldLabel: 'venName',
        component: 'ListSelect',
        componentProps: {
          selectType: 'basVenSelect',
          canSelectParent: false,
          placeholder: '供应商',
          onSelect: async (e) => {
            venData.value.id = e[0].id;
            if (companyData.value.code) {
              await reload();
              await reload3();
            }
            // setTableData3([])
          },
        },
      },
    ],
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t(''),
        field: 'num',
        component: 'InputNumber',
        // componentProps: {
        //   placeholder: t('请输入分配数量'),
        //   min:0
        // },
        componentProps: ({ formModel }) => {
          return {
            placeholder: t('请输入分配数量'),
            min: 0,
            onBlur: (e) => {
              formModel['num'] = formModel['num']
                ? formModel['num'].toFixed(NumEnum.scaleSelQty)
                : 0;
            },
          };
        },
        required: true,
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();

  const totals = computed(() => {
    let sumninnum = 0;
    let sumyzbQty = 0;
    let sumykpQty = 0;
    let sumkpzQty = 0;
    let sumsykpQty = 0;

    let sumnmny = 0;
    let sumntaxmny = 0;
    let sumnoritaxmny = 0;

    for (const record of getDataSource()) {
      console.log('record', record);
      // 计算总金额
      const {
        ninnum,
        yzbQty,
        ykpQty,
        kpzQty,
        sykpQty,
        editValueRefs: { nmny, ntaxmny },
        noritaxmny,
      } = record;

      sumninnum += Number(ninnum || 0);
      sumyzbQty += Number(yzbQty || 0);
      sumykpQty += Number(ykpQty || 0);
      sumkpzQty += Number(kpzQty || 0);
      sumsykpQty += Number(sykpQty || 0);

      sumnmny += Number(nmny || 0);
      sumntaxmny += Number(ntaxmny || 0);
      sumnoritaxmny += Number(noritaxmny || 0);
    }
    return [
      sumninnum.toFixed(NumEnum.scaleSelQty),
      sumyzbQty.toFixed(NumEnum.scaleSelQty),
      sumykpQty.toFixed(NumEnum.scaleSelQty),
      sumkpzQty.toFixed(NumEnum.scaleSelQty),
      sumsykpQty.toFixed(NumEnum.scaleSelQty),
      sumnmny.toFixed(NumEnum.scaleSelQty),
      sumntaxmny.toFixed(NumEnum.scaleSelQty),
      sumnoritaxmny.toFixed(NumEnum.scaleSelQty),
    ];
  });

  function handlefp() {
    let flag = true;
    let cinvcode = getDataSource()[0].cinvcode;
    let custName = getDataSource()[0].parent?.custName;

    for (const record of getDataSource()) {
      if (record.cinvcode != cinvcode) {
        flag = false;
      }
      if (record.parent?.custName != custName) {
        flag = false;
      }
    }
    if (flag) {
      openModal(true, {});
      resetFields();
    } else {
      showMessage('页面请保证为同一存货和供应商!');
    }
  }

  async function handleQr() {
    let data = await validate();
    let keyArr = [];
    for (const record of getDataSource()) {
      if (data.num > record.puOrderExcute.syQty) {
        record.selQty = record.puOrderExcute.syQty;
      } else {
        record.selQty = data.num;
      }
      keyArr.push(record.id);
    }
    setSelectedRowKeys(keyArr || []);
    closeModal();
  }

  async function handleAddBh() {
    if (getSelectRows().length <= 0) {
      showMessage('请先勾选后添加备货区');
      return;
    }
    let list = getSelectRows().map((item) => {
      return {
        ...item,
        sourceId: item.id,
        kpQty: item.editValueRefs.kpQty.value ? item.editValueRefs.kpQty.value : 0,
        nprice: item.editValueRefs.nprice.value ? item.editValueRefs.nprice.value : 0,
        nmny: item.editValueRefs.nmny.value ? item.editValueRefs.nmny.value : 0,
        ntaxprice: item.editValueRefs.ntaxprice.value ? item.editValueRefs.ntaxprice.value : 0,
        ntaxmny: item.editValueRefs.ntaxmny.value ? item.editValueRefs.ntaxmny.value : 0,
      };
    });
    const res = await puGeneralPreDataSave(
      { pkCorp: companyData.value.code, venId: venData.value.id },
      list,
    );
    showMessage(res.message);
    setTableData([]);
    reload();
    reload3();
    // setTableData3([])
  }

  async function handlegx() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    // if (!venData.value.id) {
    //   showMessage('请先选择供应商！');
    //   return;
    // }
    if (getSelectRows3().length <= 0) {
      showMessage('请先勾选后清除');
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      // venId: venData.value.id,
      operType: 'sel',
    };
    data.selIds = getSelectRows3()
      .map((item) => item.id)
      .join(',');
    const res = await puGeneralPreDataDelete(data);
    showMessage(res.message);
    // reload3({
    //   searchInfo: searchInfo3.value
    // })
    reload();
    reload3();
    // reload2()
    // setTableData3([])
  }

  async function handlegys() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    listSelectRefGys.value.openSelectModal();
  }
  async function handleSelectGys(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请先选择供应商'));
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      operType: 'vendor',
      venId: values[0].id,
    };
    console.log(data);
    const res = await puGeneralPreDataDelete(data);
    showMessage(res.message);
    reload();
    reload3();
    // reload2()
    // setTableData3([])
    listSelectRefGys.value.setSelectList([]);
  }

  async function handlebr() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    // if (!venData.value.id) {
    //   showMessage('请先选择供应商！');
    //   return;
    // }
    let data = {
      pkCorp: companyData.value.code,
      // venId: venData.value.id,
      operType: 'curUser',
    };
    const res = await puGeneralPreDataDelete(data);
    showMessage(res.message);
    reload();
    reload3();
    // reload2()
    // setTableData3([])
  }

  async function handlexzyh() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    // if (!venData.value.id) {
    //   showMessage('请先选择供应商！');
    //   return;
    // }
    listSelectRefUser.value.openSelectModal();
  }
  async function handleSelectUser(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请先选择用户'));
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      // venId: venData.value.id,
      operType: 'selUser',
      userCode: values[0].userCode,
    };
    const res = await puGeneralPreDataDelete(data);
    showMessage(res.message);
    reload();
    reload3();
    // reload2()
    // setTableData3([])
    listSelectRefUser.value.setSelectList([]);
  }

  async function handleGxsd() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    if (getSelectRows3().length <= 0) {
      showMessage('请先勾选后生单');
      return;
    }

    let data = {
      pkCorp: companyData.value.code,
      venId: venData.value.id,
      operType: 'sel',
    };
    data.selIds = getSelectRows3()
      .map((item) => item.id)
      .join(',');
    const res = await puGeneralPreDataPushKpBill(data);
    showMessage(res.message);
    reload();
    reload3();
    // reload2()
    // setTableData3([])
    router.push({
      path: '/srm/cw/billvouch/puBillVouch/list',
      query: {},
    });
  }
  async function handleYjsd() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    if (!venData.value.id) {
      showMessage('请先选择供应商！');
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      venId: venData.value.id,
      operType: 'all',
    };
    const res = await puGeneralPreDataPushKpBill(data);
    showMessage(res.message);
    reload();
    reload3();
    // reload2()
    // setTableData3([])
    router.push({
      path: '/srm/cw/billvouch/puBillVouch/list',
      query: {},
    });
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  // 鼠标行点击事件，获取上表数据
  function handleRowClick(record: Recordable) {
    console.log(record);
    record.onEdit?.(true, false);
    searchInfo3.value = {
      venId: record.venId,
      busType: record.busType,
      wareId: record.wareId,
      cgId: record.cgId,
      cgDeptId: record.cgDeptId,
    };
    reload3({
      searchInfo: searchInfo3.value,
    });
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  function handleSuccess2(record: Recordable) {
    reload2({ record });
  }

  onMounted(async () => {
    await setFieldsValue2({
      code: userStore.getProjecte.code,
    });
    companyData.value.code = userStore.getProjecte.code || '';
    if (venData.value.id) {
      await reload();
      await reload3();
    }
  });
  // async function handleBg() {
  //   await getForm().setFieldsValue({
  //     vordercode: router.currentRoute.value.query.vordercode,
  //   });
  //   reload();
  //   await getForm().setFieldsValue({
  //     vordercode: router.currentRoute.value.query.vordercode,
  //   });
  // }

  async function rowChange({ column, value, record }) {
    let {
      editValueRefs: { kpQty, nprice, nmny, ntaxprice, ntaxmny },
    } = record;
    if (column.dataIndex == 'kpQty') {
      kpQty.value = value.toFixed(NumEnum.scaleSelQty);
      if (value > record.sykpQty) {
        kpQty.value = record.sykpQty;
      }

      if (kpQty.value <= 0) {
        return;
      }
      // 开票数
      let data = {
        id: record.id,
        iqty: kpQty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: record.noritaxmny,
        updateType: 'iqty',
      };
      let res = await puBillVouchCalcMoney(data);
      nprice.value = res.data.fprice;
      nmny.value = res.data.fmoney;
      ntaxprice.value = res.data.ftaxPrice;
      ntaxmny.value = res.data.ftaxMoney;

      record.noritaxmny = res.data.ftax;
    }

    if (column.dataIndex == 'nprice') {
      nprice.value = value.toFixed(NumEnum.scaleSelQty);
      // 无税单价
      let data = {
        id: record.id,
        iqty: kpQty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: record.noritaxmny,
        updateType: 'fprice',
      };
      let res = await puBillVouchCalcMoney(data);
      // nprice.value = res.data.fprice
      nmny.value = res.data.fmoney;
      ntaxprice.value = res.data.ftaxPrice;
      ntaxmny.value = res.data.ftaxMoney;

      record.noritaxmny = res.data.ftax;
    }

    if (column.dataIndex == 'nmny') {
      nmny.value = value.toFixed(NumEnum.scaleSelQty);
      // 无税金额
      let data = {
        id: record.id,
        iqty: kpQty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: record.noritaxmny,
        updateType: 'fmoney',
      };
      let res = await puBillVouchCalcMoney(data);
      nprice.value = res.data.fprice;
      // nmny.value = res.data.fmoney
      ntaxprice.value = res.data.ftaxPrice;
      ntaxmny.value = res.data.ftaxMoney;

      record.noritaxmny = res.data.ftax;
    }

    if (column.dataIndex == 'ntaxprice') {
      ntaxprice.value = value.toFixed(NumEnum.scaleSelQty);
      // 含税单价
      let data = {
        id: record.id,
        iqty: kpQty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: record.noritaxmny,
        updateType: 'ftaxPrice',
      };
      let res = await puBillVouchCalcMoney(data);
      nprice.value = res.data.fprice;
      nmny.value = res.data.fmoney;
      // ntaxprice.value = res.data.ftaxPrice
      ntaxmny.value = res.data.ftaxMoney;

      record.noritaxmny = res.data.ftax;
    }

    if (column.dataIndex == 'ntaxmny') {
      ntaxmny.value = value.toFixed(NumEnum.scaleSelQty);
      // 含税金额
      let data = {
        id: record.id,
        iqty: kpQty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: record.noritaxmny,
        updateType: 'ftaxMoney',
      };
      let res = await puBillVouchCalcMoney(data);
      nprice.value = res.data.fprice;
      nmny.value = res.data.fmoney;
      ntaxprice.value = res.data.ftaxPrice;
      // ntaxmny.value = res.data.ftaxMoney

      record.noritaxmny = res.data.ftax;
    }
  }

  async function handleXzgs() {
    // companyData.value = await validate2()
    // flag.value = true
    // setTimeout(() => {
    //   // reload2()
    //   setTableData3([])
    // }, 500)
  }
</script>
<style scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }

  .title1 {
    width: 100%;
    min-height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
    /* background: #ffffff;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center; */
  }
</style>
